<!--
 * @Author: Lizhenyu
 * @Date: 2021-07-16 14:49:48
 * @FilePath: \usp-osm-frondend\src\components\NumberInput\index.vue
-->
<template>
 <el-input  :placeholder="placeholder" :value="value" @input="update" :disabled="disabled" @blur="handleBlur"></el-input>
</template>
<script type="text/ecmascript-6">
export default {
  props: {
    value: {},
    placeholder: {},
    disabled: { type: Boolean, default: false },
    limitNum: { type: Number, default: -1 },
    dotLimit: { type: Number, default: 2 }, // 小数点位数限制
    intLimit: { type: Number, defalut: -1 } // 整数位数限制
  },
  methods: {
    update (val) {
      if (this.limitNum > 0 && val > this.limitNum) return
      let str = ''
      if (this.intLimit > 0) {
        // 如果设了整数位限制
        const valueList = val.split('.')
        if (valueList.length > 1) {
          // 如果输了小数点,截取小数后dotLimit位
          if (valueList[0] === '') return
          const pattenStr = '^\\d{0,' + this.dotLimit + '}'
          const pattenReg = new RegExp(pattenStr, 'g')
          const decimals = valueList[1].match(pattenReg) || null
          this.$emit('input', valueList[0] + '.' + decimals)
          return
        } else {
          // 如果没输小数点，截取前intLimit位
          str = '^\\d{0,' + this.intLimit + '}'
        }
      } else {
        str = '^\\d*(\\.?\\d{0,' + this.dotLimit + '})'
      }
      const reg = new RegExp(str, 'g')
      const inputNum = val.match(reg)[0] || null
      this.$emit('input', inputNum)
    },
    handleBlur () {
      if (this.value) {
        const list = this.value.split('.')
        if (list.length > 1 && list[1] === '') {
          this.$emit('input', list[0])
        }
      } else {
        this.$emit('input', 0)
      }
    }
  }
}
</script>
